package com.mycompany.dewcineplanet.repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Repository;

import com.mycompany.dewcineplanet.model.Funcion;

@Repository
public class JdbcFuncionRepository {
	@Autowired
	private DataSource dataSource;
	
	private Funcion mapFuncion(ResultSet rs) throws SQLException {
		// get the row column data
		String codigo = rs.getString("codigo");
		String descripcion = rs.getString("descripcion");
		// map to the object
		Funcion funcion = new Funcion(codigo, descripcion);
		//restaurant.setBenefitPercentage(benefitPercentage);
		return funcion;
	}
	private void advanceToNextRow(ResultSet rs) throws EmptyResultDataAccessException, SQLException {
		if (!rs.next()) {
			throw new EmptyResultDataAccessException(1);
		}
	}
	public Funcion findByCodigoFuncion(String codigo) {
		String sql = "select codigo, descripcion from T_funcion where codigo = ?";
		Funcion funcion = null;
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = dataSource.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setString(1, codigo);
			rs = ps.executeQuery();
			advanceToNextRow(rs);
			funcion = mapFuncion(rs);
		} catch (SQLException e) {
			throw new RuntimeException("SQL exception occurred finding by codigo", e);
		} finally {
			if (rs != null) {
				try {
					// Close to prevent database cursor exhaustion
					rs.close();
				} catch (SQLException ex) {
				}
			}
			if (ps != null) {
				try {
					// Close to prevent database cursor exhaustion
					ps.close();
				} catch (SQLException ex) {
				}
			}
			if (conn != null) {
				try {
					// Close to prevent database connection exhaustion
					conn.close();
				} catch (SQLException ex) {
				}
			}
		}
		return funcion;
	}	
}
